import moment from 'moment';
import XLSX from '@/utils/xlsx.bundle.js';
import { saveAs } from 'file-saver';
export default {
  data() {
    return {
      orderData: [],
      outOrderData: [],
      bankAllInfo: {},
      bankList: [],
      showBank: false
    };
  },
  methods: {
    //导出订单
    async exportOrderBtnClick() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请先选择');
      } else {
        this.exportList(this.multipleSelection);
      }
    },
    getBold({ i, cell }) {
      let data = false;
      let list = ['A1', 'A2', 'A3', 'A4', 'E3', 'H3', 'H4'];
      if (list.findIndex(item => item === cell) !== -1) {
        data = true;
      } else if (i === 5) {
        data = true;
      }
      return data;
    },
    getHorizontal({ i, cell, len }) {
      let data = 'left';
      let list = ['A1', 'A2', `E${7 + len}`];
      if (list.findIndex(item => item === cell) !== -1) {
        data = 'center';
      } else if (i > 4 && i < len + 7) {
        data = 'center';
      }
      return data;
    },
    getSZ({ i, cell, len }) {
      let data = 9;
      if (i === 3 || i === 4) {
        data = 10;
      } else if (cell === 'A1' || cell === 'A2') {
        data = 14;
      } else if (i > 6 + len || i < 11 + len) {
        data = 8;
      }
      return data;
    },
    getBorder({ i, cell, max }) {
      let data = {};
      if (i > 4 && i !== max) {
        data = {
          top: { style: 'thin', color: '#000000' },
          bottom: { style: 'thin', color: '#000000' },
          left: { style: 'thin', color: '#000000' },
          right: { style: 'thin', color: '#000000' }
        };
      }
      return data;
    },
    //导出出库单
    async exportOutOrderBtnClick() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请先选择');
      } else {
        if (this.multipleSelection.length > 1) {
          if (!this.checkDuplicate(this.multipleSelection, 'customerName')) {
            this.$message.warning('请选择相同的客户');
            return;
          } else if (!this.checkDuplicate(this.multipleSelection, 'companyName')) {
            this.$message.warning('请选择相同的公司');
            return;
          }
        }
        this.bankList = [];
        let res = await this.$api.get(this.$url.exportSaleOrderList, { saleOrderIds: [this.multipleSelection[0].id] });
        this.bankAllInfo = res.data[0];
        this.bankList.push({
          bank: res.data[0].bank.split('//')[0],
          address: res.data[0].bank.split('//')[1],
          taxNo: res.data[0].taxNo,
          selected: false
        });
        if (res.data[0].address.split('//')[0] !== 'undefined') {
          this.bankList.push({
            bank: res.data[0].address.split('//')[0] === 'undefined' ? '' : res.data[0].address.split('//')[0],
            address: res.data[0].address.split('//')[1] === 'undefined' ? '' : res.data[0].address.split('//')[1],
            taxNo: res.data[0].taxNo,
            selected: false
          });
        }
        this.showBank = true;
      }
    },
    //银行弹框点击
    selectedBank(row) {
      this.bankList.forEach(el => {
        el.selected = false;
      });
      row.selected = true;
    },
    confirmBank() {
      let flag = false;
      let selectedBank;
      this.bankList.forEach(el => {
        if (el.selected) {
          selectedBank = el;
          flag = true;
        }
      });
      if (!flag) {
        this.$message.warning('请先选择');
        return;
      }
      let info = {
        bank: selectedBank.bank,
        address: selectedBank.address,
        companySalePhone: this.bankAllInfo.companySalePhone,
        taxNo: selectedBank.taxNo
      };
      this.showBank = false;
      this.exportOutOrder(info, this.multipleSelection);
    },
    //导出出库单
    exportInvoiceBtnClick() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请先选择');
      } else {
        this.exportTemplate(this.multipleSelection);
      }
    },
    //导出库存
    async exportStockBtnClick() {
      let res = await this.$api.get(this.$url.inventoryAll, { isZero: '2', pageSize: 10000, pageNum: 1 });
      if (res.rows.length === 0) {
        this.$message.warning('暂无数据');
      } else {
        this.exportStock(res.rows);
      }
    },
    //导出订单
    exportList(arr) {
      let orderList = [];
      let wpx = [{ wpx: 220 }, { wpx: 70 }, { wpx: 75 }, { wpx: 220 }, { wpx: 70 }, { wpx: 200 }, { wpx: 120 }, { wpx: 300 }, { wpx: 140 }, { wpx: 60 }, { wpx: 50 }, { wpx: 60 }, { wpx: 60 }, { wpx: 60 }, { wpx: 60 }, { wpx: 60 }, { wpx: 200 }, { wpx: 50 }, { wpx: 145 }, { wpx: 50 }, { wpx: 630 }];
      orderList.push(['公司', '业务员', '日期', '客户单位', '采购人', '品牌', '货号', '名称', '规格', '数量', '计量单位', '拿货单价', '拿货总价', '客户单价', '客户总价', '毛利', '供货商', '进项票', '发票号', '是否回款', '备注']);
      arr.map(item => {
        orderList.push([item.companyName, item.companySaleName, item.dateInput, item.customerName, item.customerPurchaserName, item.productBrandName, item.productBrandArticleNo, item.productBrandArticleNoName, item.productSpecificationName, item.qty, item.unit, item.purchaseSinglePrice, item.purchaseTotalPrice, item.customerSinglePrice, item.customerTotalPrice, Number(item.customerTotalPrice) - Number(item.purchaseTotalPrice), item.productSupplierName, item.purchaseInvoice === '1' ? '是' : '否', item.invoiceNo, item.purchaseInvoiceReceive === '1' ? '是' : '否', item.remark]);
      });
      this.handleData({ orderList, wpx, name: '订单' });
    },
    //导出出库单
    async exportOutOrder(info, arr) {
      let cellInfo = localStorage.getItem('cellInfo') || { cell1: '21.78', cell2: '57.78', cell3: '63.77', cell4: '213.77', cell5: '45.79', cell6: '27.82', cell7: '27.82', cell8: '63.78', cell9: '75.78' };
      let orderList = [];
      let wpx = [];
      let list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
      list.forEach(el => {
        wpx.push({ wpx: cellInfo[`cell${el}`] });
      });
      orderList.push([arr[0].companyName, '', '', '', '', '', '', '', '', '']);
      orderList.push(['销售出库单', '', '', '', '', '', '', '', '']);
      orderList.push(['客户名称：', '', arr[0].customerName, '', `收货人：${arr[0].customerPurchaserName}`, '', '', `电话：${arr[0].customerPurchaserPhone}`, '']);
      orderList.push(['收货地址：', '', arr[0].customerAddress, '', '', '', '', `制单日期：${moment().format('YYYY-MM-DD')}`, '']);
      orderList.push(['序号', '品牌', '货号', '品名', '规格', '单位', '数量', '含税单价', '总价']);
      let totalNum = 0;
      let totalPrice = 0;
      arr.map((item, idx) => {
        totalNum += Number(item.qty);
        totalPrice += Number(item.customerTotalPrice);
        orderList.push([idx + 1, item.productBrandName, item.productBrandArticleNo, item.productBrandArticleNoName, item.productSpecificationName, item.unit, Number(item.qty).toFixed(0), item.customerSinglePrice, item.customerTotalPrice]);
      });
      orderList.push(['', '合计', '', '', '', '', totalNum.toFixed(0), '', totalPrice.toFixed(2)]);
      orderList.push(['客户\n须知', '1、尊敬的客户，您好！以上是您所购的产品,请当面清点并核对发票。\n2、若无异议，请安排付款，付款请注明发票号，谢谢！\n3、若有货物缺少或损坏的情况，请在收到货物起三日内与我公司联系。', '', '', '供销\n单位', '公司名称', '', arr[0].companyName, '']);
      orderList.push(['', '', '', '', '', '纳税人识别号', '', info.taxNo, '']);
      orderList.push(['', '', '', '', '', '开户行', '', info.address, '']);
      orderList.push(['', '', '', '', '', '', '', info.bank, '']);
      orderList.push(['', '业务员：', arr[0].companySaleName, `电话：${info.companySalePhone}`, '签收人：', '', '', '日期', '']);
      let merges = [
        { s: { c: 0, r: 0 }, e: { c: 8, r: 0 } },
        { s: { c: 0, r: 1 }, e: { c: 8, r: 1 } },
        { s: { c: 0, r: 2 }, e: { c: 1, r: 2 } },
        { s: { c: 2, r: 2 }, e: { c: 3, r: 2 } },
        { s: { c: 4, r: 2 }, e: { c: 6, r: 2 } },
        { s: { c: 7, r: 2 }, e: { c: 8, r: 2 } },
        { s: { c: 0, r: 3 }, e: { c: 1, r: 3 } },
        { s: { c: 2, r: 3 }, e: { c: 6, r: 3 } },
        { s: { c: 7, r: 3 }, e: { c: 8, r: 3 } },
        { s: { c: 0, r: arr.length + 6 }, e: { c: 0, r: arr.length + 9 } },
        { s: { c: 1, r: arr.length + 6 }, e: { c: 3, r: arr.length + 9 } },
        { s: { c: 4, r: arr.length + 6 }, e: { c: 4, r: arr.length + 9 } },
        { s: { c: 5, r: arr.length + 6 }, e: { c: 6, r: arr.length + 6 } },
        { s: { c: 7, r: arr.length + 6 }, e: { c: 8, r: arr.length + 6 } },
        { s: { c: 5, r: arr.length + 7 }, e: { c: 6, r: arr.length + 7 } },
        { s: { c: 7, r: arr.length + 7 }, e: { c: 8, r: arr.length + 7 } },
        { s: { c: 5, r: arr.length + 8 }, e: { c: 6, r: arr.length + 9 } },
        { s: { c: 7, r: arr.length + 8 }, e: { c: 8, r: arr.length + 8 } },
        { s: { c: 7, r: arr.length + 9 }, e: { c: 8, r: arr.length + 9 } }
      ];
      this.handleData({ orderList, dataLen: arr.length, merges, wpx, name: '出库单' });
    },
    //导出发票模板
    exportTemplate(arr) {
      let wpx = [{ wpx: 200 }, { wpx: 78 }, { wpx: 75 }, { wpx: 75 }, { wpx: 75 }, { wpx: 75 }, { wpx: 100 }, { wpx: 170 }, { wpx: 75 }, { wpx: 75 }, { wpx: 75 }];
      let orderList = [];
      orderList.push([
        '填表说明：\n1、项目名称：无需写商品和服务税收分类简称（*号以及中间内容）。\n2、导入前请在电子税务局【开票业务】-【开票信息维护】中对开具的项目信息进行维护，或在导入模板中填写“商品与服务税收分类编码”。如未做项目信息维护且未填商品编码，导入会不成功。当明细超过200条时，请在模板中填写商编。\n3、数量、单价可任填其中一项，或者仅填金额；如果三项均填写，导入后系统将默认以填写的数量*单价=金额进行误差校验；\n商品单价、商品数量：小数点后最多保留13位小数；\n金额：小数点后最多保留2位小数。\n4、系统会根据折扣金额自动生成折扣行，需填写正数折扣金额；折扣金额小数点后最多保留2位小数。\n5、仅支持普通模式、货物运输服务业务、自产农产品销售业务、农产品收购业务、不动产经营租赁业务、白酒业务、报废产品收购业务、卷烟业务、电子烟业务、不动产销售业务导入项目明细但不支持上述业务商编混开，暂不支持其他特定业务模式的项目明细信息导入。\n6、开具特定业务自产农产品销售发票、特定业务农产品收购发票，税率栏次填“0”，优惠政策类型选择“免税”。\n7、目前因服务器承载原因，超过2000行后可能会导致系统异常无法开具发票，超过5000行后无法开具发票，请注意发票明细行数。\n8、“当“特定业务类型”为“白酒”时，本模版中“项目名称”、“商品和服务税收编码”、“规格型号”、“单位”请填写白酒产品编码相应信息。\n9、当“特定业务类型”为“电子烟”时，单位、数量、单价栏不允许为空，单位默认为“盒”不允许修改，数量必须为大于0的整数。\n10、当“特定业务类型”为“卷烟”时，单位、数量、单价栏不允许为空。卷烟生产企业单位为“万支”，且不可更改；卷烟批发企业单位仅提供“标准条”和“支”。\n11、当特定业务类型选择“不动产销售”时，需填写“2-特定要素信息-不动产销售”区域信息。\n12、当特定业务类型选择“不动产经营租赁服务”时，需填写“2-特定要素信息-不动产租赁”区域信息。\n13、当“商品和服务税收分类编码”填写原煤（1020101000000000000）、洗煤（1020102000000000000）、其他煤炭采选产品（1020199000000000000）时，本模版中“煤炭种类”需填写。',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        ''
      ]);
      orderList.push(['必填\n(限100字符)', '非必填\n(限19字符)', '非必填\n(限40字符)', '非必填\n(限20字符)', '非必填\n(限16字符)', '非必填\n(限16字符)', '必填\n(限18字符)\n(保留两位小数)', "必填\n(以小数后两位形式填写，如'0.13'代表税率13%)", '非必填\n(限18字符)\n保留两位小数', '非必填\n(限15字符)', '非必填\n(限15字符)']);
      orderList.push(['项目名称', '商品和服务税收\n分类编码', '规格型号', '单位', '商品数量', '商品单价', '金额', '税率', '折扣金额', '优惠政策类型', '煤炭种类']);
      arr.map(item => {
        orderList.push([
          item.productBrandArticleNoName,
          item.taxCode ? item.taxCode.split('-').pop() : '', // 商品和服务税收分类编码（只保留-后面的字符串）
          item.productSpecificationName || '', // 规格型号
          item.unit || '', // 单位
          item.qty || '', // 商品数量
          item.customerSinglePrice || '', // 商品单价
          item.customerTotalPrice, // 金额
          0.01, // 税率
          '', // 折扣金额
          '', // 优惠政策类型
          '' // 煤炭种类(保持为空)
        ]);
      });
      let merges = [{ s: { c: 0, r: 0 }, e: { c: 10, r: 0 } }];
      this.handleData({ orderList, wpx, merges, name: '发票信息模板' });
    },
    //导出库存
    exportStock(list) {
      let wpx = [{ wpx: 220 }, { wpx: 200 }, { wpx: 120 }, { wpx: 300 }, { wpx: 140 }, { wpx: 60 }, { wpx: 60 }, { wpx: 60 }, { wpx: 200 }, { wpx: 630 }];
      let orderList = [];
      orderList.push(['公司', '品牌', '货号', '名称', '规格', '数量', '单价', '库存总价', '供货商', '备注']);
      list.map(item => {
        orderList.push([item.companyName, item.productBrandName, item.productBrandArticleNo, item.productBrandArticleNoName, item.productSpecificationName, item.qty, item.singlePrice, Number(item.singlePrice) * Number(item.qty), item.productSupplierName, item.remark]);
      });
      this.handleData({ orderList, wpx, name: '库存' });
    },
    //处理导出数据
    async handleData(nv) {
      let data = JSON.parse(JSON.stringify(nv));
      if (data.orderList && data.orderList.length > 0) {
        let worksheet = XLSX.utils.json_to_sheet(data.orderList, { skipHeader: true });
        if (data.name === '订单') {
          for (const key in worksheet) {
            if (worksheet[key] instanceof Object) {
              worksheet[key].s = {
                alignment: { vertical: 'center', horizontal: 'center', indent: 0, wrapText: true },
                font: { name: '宋体', sz: 10, color: { rgb: '#FF000000' }, bold: false, italic: false, underline: false }
              };
            }
          }
        } else if (data.name === '出库单') {
          let zm = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
          for (let i = 1; i < data.dataLen + 12; i++) {
            for (let j = 0; j < zm.length; j++) {
              worksheet[`${zm[j]}${i}`].s = {
                alignment: { vertical: 'center', horizontal: this.getHorizontal({ i, cell: `${zm[j]}${i}`, len: data.dataLen }), indent: 0, wrapText: true },
                font: { name: '宋体', sz: this.getSZ({ i, cell: `${zm[j]}${i}`, len: data.dataLen }), color: { rgb: '#FF000000' }, bold: this.getBold({ i, cell: `${zm[j]}${i}` }), italic: false, underline: false },
                border: this.getBorder({ i, max: data.dataLen + 11 })
              };
            }
          }
        } else if (data.name === '库存') {
          let zm = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
          for (let i = 1; i < data.dataLen + 12; i++) {
            for (let j = 0; j < zm.length; j++) {
              worksheet[`${zm[j]}${i}`].s = {
                alignment: { vertical: 'center', horizontal: 'center', indent: 0, wrapText: true },
                font: { name: '宋体', sz: 9, color: { rgb: '#FF000000' }, bold: false, italic: false, underline: false },
                fill: { fgColor: { rgb: 'FFFF00' } }
              };
            }
          }
        } else {
          // 为A1单元格设置样式，确保合并单元格也能正确换行
          worksheet.A1 = {
            v: worksheet.A1.v, // 保留原始值
            t: 's', // 字符串类型
            s: {
              alignment: { vertical: 'center', horizontal: 'left', indent: 0, wrapText: true },
              font: { name: '宋体', sz: 9, bold: false, italic: false, underline: false },
              fill: { fgColor: { rgb: 'CCFFFF' } }
            }
          };
          let zm = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'];
          for (let j = 0; j < zm.length; j++) {
            worksheet[`${zm[j]}2`].s = {
              alignment: { vertical: 'center', horizontal: 'center', indent: 0, wrapText: true },
              font: { name: '宋体', sz: 9, color: { rgb: '#FF000000' }, bold: false, italic: false, underline: false },
              fill: { fgColor: { rgb: 'FFFF00' } }
            };
            worksheet[`${zm[j]}3`].s = {
              alignment: { vertical: 'center', horizontal: 'center', indent: 0, wrapText: true },
              font: { name: '宋体', sz: 9, color: { rgb: '#FF000000' }, bold: false, italic: false, underline: false }
            };
          }
        }
        worksheet['!merges'] = data.merges;
        worksheet['!cols'] = data.wpx;
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1'); // sheet1 是自定义的sheet名
        // XLSX.write 会根据type返回值，为什么选择binary类型，因为binary好歹是个string，H5+的io写入api只支持写入string类型的
        let binaryData = XLSX.write(workbook, { bookType: 'xlsx', bookSST: false, type: 'binary' });
        const buf = new ArrayBuffer(binaryData.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== binaryData.length; ++i) {
          view[i] = binaryData.charCodeAt(i) & 0xff;
        }
        const d = new Date();
        let startTime = `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日${d.getHours()}时${d.getMinutes()}分${d.getSeconds()}秒`;
        let fileName = `${data.name}${startTime}.xlsx`;
        let blobData = new Blob([buf], { type: 'application/octer-stream' });
        saveAs(blobData, fileName);
        let fileItem = data.name === '订单' ? 'order' : data.name === '出库单' ? 'outOrder' : 'ticket';
        let fileList = (await this.$excelDB.getItem(fileItem)) || [];
        fileList.push({ fileName, blobData });
        this.$excelDB.setItem(fileItem, fileList);
      }
    },
    //检测重复属性
    checkDuplicate(array, key) {
      let values = new Set();
      for (let i = 0; i < array.length; i++) {
        let value = array[i][key];
        if (values.has(value)) {
          return true;
        }
        values.add(value);
      }
      return false;
    }
  }
};
